<template>
  <div class="check-history-container">
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item :label="$t('attendance.status')">
          <el-select v-model="filterForm.state" :placeholder="$t('attendance.approvalStatus')" clearable>
            <el-option :label="$t('attendance.checkAdmin.all')" :value="null"></el-option>
            <el-option :label="$t('attendance.checkAdmin.pending')" :value="0"></el-option>
            <el-option :label="$t('attendance.checkAdmin.approved')" :value="1"></el-option>
            <el-option :label="$t('attendance.checkAdmin.rejected')" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('attendance.dateRange')">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            :range-separator="$t('common.to')"
            :start-placeholder="$t('attendance.startDate')"
            :end-placeholder="$t('attendance.endDate')"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">{{ $t('common.search') }}</el-button>
          <el-button @click="resetFilter">{{ $t('common.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table
      :data="filteredLeaveList"
      style="width: 100%"
      border
      v-loading="loading">
      <el-table-column
        :label="$t('course.title')"
        min-width="120">
        <template slot-scope="scope">
          {{ getCourseName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.leaveType')"
        min-width="100">
        <template slot-scope="scope">
          <el-tag size="medium">{{ getLeaveTypeName(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.leaveTime')"
        min-width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.leaveDate) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.leaveReason')"
        min-width="200">
        <template slot-scope="scope">
          {{ scope.row.reason }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.approvalStatus')"
        min-width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.state)">
            {{ getStatusText(scope.row.state) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.checkAdmin.approvalOpinion')"
        min-width="200">
        <template slot-scope="scope">
          {{ scope.row.approveRemark }}
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container" v-if="totalPages > 1">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import ElementUI from "element-ui";

export default {
  name: "LeaveStudentHistory",
  data() {
    return {
      filterForm: {
        state: null,
        dateRange: []
      },
      leaveList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalPages: 0,
      total: 0,
      courseMap: {}, // 存储课程ID和名称的映射
      leaveTypes: [], // 存储请假类型列表
      leaveTypeMap: {} // 请假类型ID和名称的映射
    }
  },
  computed: {
    filteredLeaveList() {
      let result = [...this.leaveList];
      
      // 根据状态筛选
      if (this.filterForm.state !== null) {
        result = result.filter(item => item.state === this.filterForm.state);
      }
      
      // 根据日期范围筛选
      if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
        const startDate = new Date(this.filterForm.dateRange[0]);
        const endDate = new Date(this.filterForm.dateRange[1]);
        endDate.setHours(23, 59, 59, 999); // 设置为当天结束时间
        
        result = result.filter(item => {
          const leaveDate = new Date(item.leaveDate);
          return leaveDate >= startDate && leaveDate <= endDate;
        });
      }
      
      // 更新分页信息
      this.total = result.length;
      this.totalPages = Math.ceil(this.total / this.pageSize);
      
      // 分页处理
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return result.slice(start, end);
    }
  },
  created() {
    this.loadCourses(); // 加载课程信息
    this.loadLeaveTypes(); // 加载请假类型
    this.loadData(); // 加载请假记录
  },
  methods: {
    // 加载课程信息
    loadCourses() {
      this.$axios.get("/course/page", { 
        params: {
          current: 1,
          size: 1000 // 设置较大的页面大小以获取所有课程
        }
      }).then(res => {
        if (res.code === 200) {
          const courses = res.data.records || [];
          // 构建课程ID到课程名称的映射
          this.courseMap = {};
          courses.forEach(course => {
            this.courseMap[course.id] = course.name;
          });
        } else {
          this.$message.error(res.data.msg || this.$t('course.getCoursesError'));
        }
      }).catch(error => {
        console.error('获取课程列表失败:', error);
        this.$message.error(this.$t('common.operationFailedRetry'));
      });
    },
    
    // 加载请假类型
    loadLeaveTypes() {
      this.$axios.get("/leave/types").then(res => {
        if (res.code === 200) {
          this.leaveTypes = res.data || [];
          // 构建请假类型ID到名称的映射
          this.leaveTypeMap = {};
          this.leaveTypes.forEach(type => {
            this.leaveTypeMap[type.id] = type.name;
          });
        } else {
          this.$message.error(res.data.msg || this.$t('attendance.checkAdmin.getCourseFailed'));
        }
      }).catch(error => {
        console.error('获取请假类型列表失败:', error);
        this.$message.error(this.$t('common.operationFailedRetry'));
      });
    },
    
    // 加载请假记录数据
    loadData() {
      this.loading = true;
      const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      if (!userInfo || !userInfo.userId) {
        this.$message.error(this.$t('user.loginRequired'));
        this.loading = false;
        return;
      }

      this.$axios.get(`/leave/user-history/${userInfo.userId}`).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.leaveList = res.data || [];
          this.total = this.leaveList.length;
          this.totalPages = Math.ceil(this.total / this.pageSize);
        } else {
          this.$message.error(res.data.msg || this.$t('attendance.checkAdmin.noHistoryRecords'));
        }
      }).catch((error) => {
        console.error('请求失败:', error);
        this.loading = false;
        this.$message.error(this.$t('common.operationFailedRetry'));
      });
    },
    
    // 处理筛选
    handleFilter() {
      this.currentPage = 1;
    },
    
    // 重置筛选
    resetFilter() {
      this.filterForm = {
        state: null,
        dateRange: []
      };
      this.currentPage = 1;
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    },
    
    // 获取状态文本
    getStatusText(state) {
      const statusMap = {
        0: this.$t('attendance.checkAdmin.pending'),
        1: this.$t('attendance.checkAdmin.approved'),
        2: this.$t('attendance.checkAdmin.rejected')
      };
      return statusMap[state] || this.$t('common.unknown');
    },
    
    // 获取状态标签类型
    getStatusType(state) {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      };
      return typeMap[state] || '';
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
    },

    getCourseName(row) {
      // 首先检查是否已有课程名称
      if (row.courseName) return row.courseName;
      // 如果有courseId，从课程映射中获取名称
      if (row.courseId && this.courseMap[row.courseId]) {
        return this.courseMap[row.courseId];
      }
      return this.$t('course.noDescription');
    },
    
    getLeaveTypeName(row) {
      // 如果直接有reason字段（旧数据），返回这个
      if (row.reason && typeof row.reason === 'string' && !row.leaveTypeId) {
        return row.reason;
      }
      
      // 如果有leaveTypeId，从请假类型映射中获取名称
      if (row.leaveTypeId && this.leaveTypeMap[row.leaveTypeId]) {
        const typeName = this.leaveTypeMap[row.leaveTypeId];
        
        // 对常见的请假类型进行国际化转换
        const typeTranslateMap = {
          '病假': 'attendance.checkAdmin.sickLeave',
          '事假': 'attendance.checkAdmin.personalLeave',
          '其他请假': 'attendance.checkAdmin.otherLeave'
        };
        
        // 如果是预设的请假类型，则使用国际化翻译
        if (typeTranslateMap[typeName]) {
          return this.$t(typeTranslateMap[typeName]);
        }
        
        // 对于其他未预设的请假类型，直接返回原始名称
        return typeName;
      }
      
      return this.$t('common.unknown');
    }
  }
}
</script>

<style scoped>
.check-history-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

@media screen and (max-width: 768px) {
  .check-history-container {
    padding: 10px;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .pagination-container {
    text-align: center;
  }
}
</style>